package com.ruizhong.integratedmediawithoutc.controller;

import com.ruizhong.integratedmediawithoutc.service.TUserService;
import com.ruizhong.integratedmediawithoutc.util.CMD;
import com.ruizhong.integratedmediawithoutc.util.Result;
import com.ruizhong.integratedmediawithoutc.util.ResultCode;
import com.ruizhong.integratedmediawithoutc.util.TCPUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/user/api")
@CrossOrigin
public class UserController {

    @Autowired
    private TUserService tUserService;

    @PostMapping("/userLogin")
    public Result userLogin(@RequestBody Map<String, Object> conditionMap) {
        ArrayList dataList = (ArrayList) conditionMap.get("data");
        HashMap<String, String> loginForm = (HashMap<String, String>) dataList.get(0);
        String token = tUserService.userLogin(loginForm);
        return new Result(ResultCode.success, null, token);
    }

    @GetMapping("/logout/{userName}")
    public Result logout(@PathVariable(value = "userName") String userName) {
        HashMap<String, Object> conditionMap = new HashMap<>();
        conditionMap.put("command", CMD.Logout.ordinal());
        conditionMap.put("user_name", userName);
        conditionMap.put("data", null);
        Map<String, Object> resMap = TCPUtil.send(conditionMap);
        return new Result(ResultCode.success, null, resMap);
    }

    @GetMapping("/getRandomId")
    public Result getRandomId(HttpServletRequest request) throws NoSuchAlgorithmException {
        String randomId = UUID.randomUUID().toString();
        return new Result<>(ResultCode.success, null, randomId);
    }
}
